<template>
  <div>
    <!-- Complete State -->
    <div v-if="state === 'complete'" class="max-w-2xl mx-auto space-y-6">
      <Card>
        <CardHeader class="text-center">
          <CardTitle class="flex items-center justify-center gap-2">
            <Brain class="w-6 h-6 text-purple-500" />
            {{ t("memoryTest.testComplete") }}
          </CardTitle>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="text-center space-y-4">
            <div class="text-6xl font-bold text-primary">
              {{ calculateFinalScore(scores, currentLevel) }}
            </div>
            <div :class="`text-xl font-semibold ${rating.color}`">
              {{ rating.text }}
            </div>
            <div class="text-lg">
              {{ t("memoryTest.completedLevels") }}:
              <span class="font-bold text-primary">{{ currentLevel }}</span>
            </div>
          </div>

          <div class="grid grid-cols-2 gap-4">
            <div class="text-center p-4 bg-muted rounded-lg">
              <div class="text-2xl font-bold">{{ currentLevel }}</div>
              <div class="text-sm text-muted-foreground">
                {{ t("memoryTest.completedLevels") }}
              </div>
            </div>
            <div class="text-center p-4 bg-muted rounded-lg">
              <div class="text-2xl font-bold">
                {{ calculateAverageScore(scores) }}%
              </div>
              <div class="text-sm text-muted-foreground">
                {{ t("memoryTest.averageAccuracy") }}
              </div>
            </div>
          </div>

          <div class="space-y-2">
            <h3 class="font-semibold">{{ t("memoryTest.levelScores") }}</h3>
            <div class="grid grid-cols-4 gap-2">
              <div
                v-for="(score, index) in scores"
                :key="index"
                class="text-center p-2 bg-muted rounded"
              >
                <div class="font-semibold">{{ score }}%</div>
                <div class="text-xs text-muted-foreground">
                  {{ t("memoryTest.level", { level: index + 1 }) }}
                </div>
              </div>
            </div>
          </div>

          <div class="flex gap-4">
            <Button
              @click="resetTest"
              variant="outline"
              class="flex-1 border-2 border-slate-300 hover:border-purple-500 hover:bg-purple-50 hover:text-purple-700 transition-all duration-200"
            >
              <RotateCcw class="w-4 h-4 mr-2" />
              {{ t("memoryTest.retest") }}
            </Button>
            <Button
              @click="handleComplete"
              class="flex-1 bg-gradient-to-r from-purple-500 to-pink-500 text-white hover:from-purple-600 hover:to-pink-600 shadow-md hover:shadow-lg transition-all duration-200"
            >
              {{ t("memoryTest.saveResult") }}
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>

    <!-- Test in Progress -->
    <div v-else class="max-w-2xl mx-auto space-y-6">
      <Card>
        <CardContent class="pt-6">
          <div class="flex justify-between items-center mb-2">
            <span class="text-sm"
              >{{ t("memoryTest.levelProgress") }}{{ currentLevel }}</span
            >
            <span class="text-sm"
              >{{ currentLevel }}/{{ MEMORY_TEST_CONFIG.MAX_LEVELS }}</span
            >
          </div>
          <Progress
            :model-value="(currentLevel / MEMORY_TEST_CONFIG.MAX_LEVELS) * 100"
          />
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle class="flex items-center justify-between">
            <div class="flex items-center gap-2">
              <Brain class="w-5 h-5 text-purple-500" />
              {{ t("memoryTest.memoryTestTitle") }} -
              {{ t("memoryTest.levelTitle", { level: currentLevel + 1 }) }}
            </div>
            <Badge
              v-if="state === 'memorize'"
              variant="secondary"
              class="flex items-center gap-1"
            >
              <Timer class="w-3 h-3" />
              {{ displayTime }}{{ t("memoryTest.seconds") }}
            </Badge>
          </CardTitle>
        </CardHeader>
        <CardContent class="space-y-6">
          <!-- Ready State -->
          <div v-if="state === 'ready'" class="text-center space-y-6">
            <div>
              <h2 class="text-xl font-bold mb-2">
                {{ t("memoryTest.levelTitle", { level: currentLevel + 1 }) }}
              </h2>
              <p class="text-muted-foreground mb-4">
                {{ t("memoryTest.memorizeInstruction") }}
              </p>
              <div class="flex justify-center gap-4">
                <Badge variant="outline">
                  {{ currentLevel + 2 }} {{ t("memoryTest.blocks") }}
                </Badge>
                <Badge variant="outline">
                  {{ calculateMemorizeTime(currentLevel) }}
                  {{ t("memoryTest.memorizeTime") }}
                </Badge>
              </div>
            </div>
            <Button
              size="lg"
              @click="startLevel"
              class="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
            >
              <Brain class="w-5 h-5 mr-2" />
              {{ t("memoryTest.startLevel", { level: currentLevel + 1 }) }}
            </Button>
          </div>

          <!-- Memorize or Recall State -->
          <div
            v-if="state === 'memorize' || state === 'recall'"
            class="space-y-4"
          >
            <div class="text-center">
              <div class="flex items-center justify-center gap-4 mb-4">
                <template v-if="state === 'memorize'">
                  <Eye class="w-5 h-5 text-blue-500" />
                  <span>{{ t("memoryTest.memorizeBlocks") }}</span>
                </template>
                <template v-else>
                  <EyeOff class="w-5 h-5 text-green-500" />
                  <span
                    >{{ t("memoryTest.clickInOrder") }} ({{
                      userSequence.length
                    }}/{{ sequence.length }})</span
                  >
                </template>
              </div>
            </div>

            <MemoryTestGrid
              :grid="grid"
              :sequence="sequence"
              :showSequence="showSequence"
              @cell-click="handleCellClick"
              :isInteractive="state === 'recall'"
            />

            <div
              v-if="
                state === 'recall' && userSequence.length === sequence.length
              "
              class="text-center p-4 bg-muted rounded-lg"
            >
              <p class="font-semibold">
                {{
                  userSequence.every((id, index) => id === sequence[index])
                    ? t("memoryTest.perfectNextLevel")
                    : t("memoryTest.partialCorrectNextLevel")
                }}
              </p>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Scores Display -->
      <Card v-if="scores.length > 0">
        <CardHeader>
          <CardTitle class="flex items-center gap-2">
            <Target class="w-5 h-5" />
            {{ t("memoryTest.currentScore") }}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div class="grid grid-cols-3 gap-4 text-center">
            <div>
              <div class="text-2xl font-bold">
                {{ calculateAverageScore(scores) }}%
              </div>
              <div class="text-sm text-muted-foreground">
                {{ t("memoryTest.averageAccuracy") }}
              </div>
            </div>
            <div>
              <div class="text-2xl font-bold">{{ currentLevel }}</div>
              <div class="text-sm text-muted-foreground">
                {{ t("memoryTest.completedLevels") }}
              </div>
            </div>
            <div>
              <div class="text-2xl font-bold">
                {{ scores[scores.length - 1] || 0 }}%
              </div>
              <div class="text-sm text-muted-foreground">
                {{ t("memoryTest.lastLevel") }}
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Instructions -->
      <Card>
        <CardContent class="pt-6">
          <h3 class="font-semibold mb-2">
            {{ t("memoryTest.testInstructionsTitle") }}
          </h3>
          <ul class="text-sm text-muted-foreground space-y-1">
            <li>{{ t("memoryTest.instruction1") }}</li>
            <li>{{ t("memoryTest.instruction2") }}</li>
            <li>{{ t("memoryTest.instruction3") }}</li>
            <li>{{ t("memoryTest.instruction4") }}</li>
            <li>{{ t("memoryTest.instruction5") }}</li>
          </ul>
        </CardContent>
      </Card>
    </div>
  </div>
</template>

<script>
import { Brain, Timer, Target, RotateCcw, Eye, EyeOff } from "lucide-vue-next";
import { useI18n } from "vue-i18n";

export default {
  components: {
    Brain,
    Timer,
    Target,
    RotateCcw,
    Eye,
    EyeOff,
    // Make sure to import and register your UI components (Card, Button, etc.)
  },

  props: {
    onComplete: {
      type: Function,
      required: true,
    },
  },

  data() {
    return {
      state: "ready",
      currentLevel: 0,
      grid: [],
      sequence: [],
      userSequence: [],
      memorizeTime: 3,
      displayTime: 3,
      scores: [],
      showSequence: false,
      testStartTime: 0,
      MEMORY_TEST_CONFIG: {
        MAX_LEVELS: 10,
        SEQUENCE_COMPLETION_DELAY: 1500,
      },
    };
  },

  setup() {
    const { t } = useI18n();
    return { t };
  },

  computed: {
    rating() {
      return this.getRating(
        this.calculateFinalScore(this.scores, this.currentLevel)
      );
    },
  },

  methods: {
    generateSequence(level) {
      const size = level + 2;
      const sequence = [];
      const totalCells = 16; // 4x4 grid

      while (sequence.length < size) {
        const randomCell = Math.floor(Math.random() * totalCells) + 1;
        if (!sequence.includes(randomCell)) {
          sequence.push(randomCell);
        }
      }
      return sequence;
    },

    calculateMemorizeTime(level) {
      return Math.max(3, 5 - Math.floor(level / 3));
    },

    createInitialGrid() {
      return Array.from({ length: 16 }, (_, i) => ({
        id: i + 1,
        isHighlighted: false,
        isSelected: false,
      }));
    },

    calculateLevelScore(userSeq, correctSeq) {
      let correct = 0;
      for (let i = 0; i < correctSeq.length; i++) {
        if (userSeq[i] === correctSeq[i]) {
          correct++;
        }
      }
      return Math.round((correct / correctSeq.length) * 100);
    },

    calculateAverageScore(scores) {
      if (scores.length === 0) return 0;
      const sum = scores.reduce((a, b) => a + b, 0);
      return Math.round(sum / scores.length);
    },

    calculateFinalScore(scores, level) {
      const average = this.calculateAverageScore(scores);
      const levelBonus = Math.min(level - 1, 10) * 2;
      return Math.min(100, average + levelBonus);
    },

    getRating(score) {
      if (score >= 90)
        return {
          text: this.t("memoryTest.ratingExcellent"),
          color: "text-green-500",
        };
      if (score >= 75)
        return {
          text: this.t("memoryTest.ratingGood"),
          color: "text-blue-500",
        };
      if (score >= 50)
        return {
          text: this.t("memoryTest.ratingAverage"),
          color: "text-yellow-500",
        };
      return {
        text: this.t("memoryTest.ratingNeedsPractice"),
        color: "text-red-500",
      };
    },

    updateGridWithCorrectness(grid, userSeq, correctSeq) {
      return grid.map((cell) => {
        const isInCorrectPos = correctSeq.includes(cell.id);
        const userSelected = userSeq.includes(cell.id);
        const correctPos =
          userSeq.indexOf(cell.id) === correctSeq.indexOf(cell.id);

        return {
          ...cell,
          isCorrect: isInCorrectPos && userSelected && correctPos,
        };
      });
    },

    shouldCompleteTest(level, score) {
      return score < 50 || level >= this.MEMORY_TEST_CONFIG.MAX_LEVELS;
    },

    createTestResult(scores, level, startTime, memorizeTime) {
      const duration = (Date.now() - startTime) / 1000;
      const finalScore = this.calculateFinalScore(scores, level);

      return {
        id: "memory-" + Date.now(),
        testType: "memory",
        score: finalScore,
        maxScore: 100,
        completedAt: new Date(),
        duration,
        percentile: Math.min(99, Math.max(1, finalScore)),
        difficulty: this.getRating(finalScore).text.toLowerCase(),
        details: {
          averageTime: memorizeTime,
          itemsRemembered: scores.filter((s) => s >= 50).length,
          totalItems: scores.length,
          totalRounds: level - 1,
        },
      };
    },

    generateLevel() {
      const newGrid = this.createInitialGrid();
      const newSequence = this.generateSequence(this.currentLevel);
      const timeNeeded = this.calculateMemorizeTime(this.currentLevel);

      this.sequence = newSequence;
      this.grid = newGrid;
      this.userSequence = [];
      this.memorizeTime = timeNeeded;
      this.displayTime = timeNeeded;
    },

    startLevel() {
      this.generateLevel();
      this.state = "memorize";
      this.showSequence = true;
      this.testStartTime = Date.now();

      setTimeout(() => {
        this.showSequence = false;
        this.state = "recall";
      }, this.memorizeTime * 1000);
    },

    handleCellClick(cellId) {
      if (this.state !== "recall") return;

      this.userSequence = [...this.userSequence, cellId];

      this.grid = this.grid.map((cell) =>
        cell.id === cellId ? { ...cell, isSelected: true } : cell
      );

      if (this.userSequence.length === this.sequence.length) {
        const finalScore = this.calculateLevelScore(
          this.userSequence,
          this.sequence
        );
        this.scores = [...this.scores, finalScore];

        this.grid = this.updateGridWithCorrectness(
          this.grid,
          this.userSequence,
          this.sequence
        );

        setTimeout(() => {
          if (this.shouldCompleteTest(this.currentLevel, finalScore)) {
            this.state = "complete";
          } else {
            this.currentLevel++;
            this.state = "ready";
          }
        }, this.MEMORY_TEST_CONFIG.SEQUENCE_COMPLETION_DELAY);
      }
    },

    resetTest() {
      this.state = "ready";
      this.currentLevel = 1;
      this.grid = [];
      this.sequence = [];
      this.userSequence = [];
      this.scores = [];
      this.showSequence = false;
      this.testStartTime = 0;
      this.memorizeTime = 3;
      this.displayTime = 3;
    },

    handleComplete() {
      const result = this.createTestResult(
        this.scores,
        this.currentLevel,
        this.testStartTime,
        this.memorizeTime
      );
      this.$emit("complete", result);
    },
  },

  watch: {
    state(newVal, oldVal) {
      if (newVal === "memorize") {
        this.interval = setInterval(() => {
          if (this.displayTime <= 1) {
            clearInterval(this.interval);
            this.displayTime = 0;
          } else {
            this.displayTime--;
          }
        }, 1000);
      } else {
        this.displayTime = this.memorizeTime;
        if (this.interval) {
          clearInterval(this.interval);
        }
      }
    },
  },

  beforeUnmount() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  },
};
</script>
